/**
 * 镜像更新服务 - 业务逻辑封装
 */

import { apiClient } from './apiClient.js'
import { useImageUpdateStore } from '../stores/imageUpdateStore.js'

/**
 * 步骤枚举
 */
export const STEP_TYPES = {
  LWX_PARSE: 'lwx_parse',
  IMAGE_VERIFY: 'image_verify', 
  CONDITIONAL_PULL: 'conditional_pull',
  CONTAINER_REBUILD: 'container_rebuild'
}

/**
 * 步骤状态枚举
 */
export const STEP_STATUS = {
  PENDING: 'pending',
  RUNNING: 'running',
  SUCCESS: 'success',
  ERROR: 'error',
  SKIPPED: 'skipped'
}

/**
 * 操作类型枚举
 */
export const ACTION_TYPES = {
  NONE: 'none',
  RESTART: 'restart',
  UPDATE: 'update',
  REBUILD: 'rebuild',
  CREATE: 'create'
}

/**
 * 镜像更新服务类
 */
export class ImageUpdateService {
  constructor() {
    this.store = null // 将在Vue组件中注入
  }

  /**
   * 设置状态管理store
   */
  setStore(store) {
    this.store = store
  }

  /**
   * 执行单个步骤（手动模式）
   */
  async executeStep(stepType, stepData = {}) {
    if (!this.store) {
      throw new Error('Store未初始化')
    }

    try {
      // 设置步骤为运行中
      this.store.setStepStatus(stepType, STEP_STATUS.RUNNING)
      
      let result = null
      
      switch (stepType) {
        case STEP_TYPES.LWX_PARSE:
          result = await this._executeLwxParseStep(stepData)
          break
          
        case STEP_TYPES.IMAGE_VERIFY:
          result = await this._executeImageVerifyStep(stepData)
          break
          
        case STEP_TYPES.CONDITIONAL_PULL:
          result = await this._executeConditionalPullStep(stepData)
          break
          
        case STEP_TYPES.CONTAINER_REBUILD:
          result = await this._executeContainerRebuildStep(stepData)
          break
          
        default:
          throw new Error(`未知的步骤类型: ${stepType}`)
      }
      
      // 设置步骤为成功
      this.store.setStepStatus(stepType, STEP_STATUS.SUCCESS, result.message)
      this.store.setStepData(stepType, result.data)
      
      return result
      
    } catch (error) {
      console.error(`步骤执行失败 [${stepType}]:`, error)
      
      // 设置步骤为失败
      this.store.setStepStatus(stepType, STEP_STATUS.ERROR, error.message)
      
      throw error
    }
  }

  /**
   * 执行完整工作流（自动模式）
   */
  async executeCompleteWorkflow(forceUpdate = false) {
    if (!this.store) {
      throw new Error('Store未初始化')
    }

    try {
      // 重置所有步骤
      this.store.resetAllSteps()
      this.store.setMode('auto')
      
      // 启动完整工作流
      const response = await apiClient.post('/api/intelligent-updates/v2/complete-workflow', {
        force_update: forceUpdate
      })
      const result = response.data
      
      // 开始监听进度更新
      this._startProgressMonitoring()
      
      return result
      
    } catch (error) {
      console.error('完整工作流执行失败:', error)
      this.store.addLog('error', `完整工作流执行失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 重试失败的步骤
   */
  async retryStep(stepType) {
    if (!this.store) {
      throw new Error('Store未初始化')
    }

    const stepData = this.store.getStepData(stepType)
    return await this.executeStep(stepType, stepData)
  }

  /**
   * 跳过步骤
   */
  skipStep(stepType, reason = '用户手动跳过') {
    if (!this.store) {
      throw new Error('Store未初始化')
    }

    this.store.setStepStatus(stepType, STEP_STATUS.SKIPPED, reason)
    this.store.addLog('warning', `步骤 ${stepType} 已跳过: ${reason}`)
  }

  /**
   * 执行LWX平台数据解析步骤
   */
  async _executeLwxParseStep(stepData) {
    this.store.addLog('info', '开始LWX平台数据解析...')
    
    const triggerSync = stepData.triggerSync || false
    const response = await apiClient.post('/api/intelligent-updates/v2/lwx-parse', {
      trigger_sync: triggerSync
    })
    const result = response.data
    
    if (result.success) {
      this.store.addLog('success', `LWX平台数据解析完成: ${result.data.school_name}`)
      
      // 保存解析结果供后续步骤使用
      this.store.updateStepContext({
        schoolName: result.data.school_name,
        schoolId: result.data.school_id,
        baseImage: result.data.base_image,
        fullImageUrl: result.data.full_image_url,
        composeFile: result.data.compose_file,
        containerName: result.data.container_name,
        patternInfo: result.data.pattern_info
      })
    }
    
    return result
  }

  /**
   * 执行镜像版本校验步骤
   */
  async _executeImageVerifyStep(stepData) {
    this.store.addLog('info', '开始智能镜像版本校验...')
    
    const context = this.store.getStepContext()
    const fullImageUrl = stepData.fullImageUrl || context.fullImageUrl
    const containerName = stepData.containerName || context.containerName
    
    if (!fullImageUrl || !containerName) {
      throw new Error('缺少镜像URL或容器名称，请先执行LWX平台数据解析')
    }
    
    const response = await apiClient.post('/api/intelligent-updates/v2/image-verify', {
      image_url: fullImageUrl,
      container_name: containerName
    })
    const result = response.data
    
    if (result.success) {
      const verificationResult = result.data.verification_result
      this.store.addLog('info', `镜像版本校验完成: ${verificationResult.reason}`)
      
      // 保存校验结果
      this.store.updateStepContext({
        actionType: verificationResult.action_type,
        needsAction: verificationResult.needs_action,
        nextSteps: result.data.next_steps
      })
    }
    
    return result
  }

  /**
   * 执行条件性镜像拉取步骤
   */
  async _executeConditionalPullStep(stepData) {
    const context = this.store.getStepContext()
    const actionType = stepData.actionType || context.actionType
    const fullImageUrl = stepData.fullImageUrl || context.fullImageUrl
    
    if (!actionType || !fullImageUrl) {
      throw new Error('缺少操作类型或镜像URL，请先执行前置步骤')
    }
    
    this.store.addLog('info', `开始条件性镜像拉取 (操作类型: ${actionType})...`)
    
    const response = await apiClient.post('/api/intelligent-updates/v2/conditional-pull', {
      action_type: actionType,
      image_url: fullImageUrl
    })
    const result = response.data
    
    if (result.success) {
      if (result.data.skipped) {
        this.store.addLog('info', `镜像拉取已跳过: ${result.data.reason}`)
      } else {
        this.store.addLog('success', `镜像拉取成功: ${result.data.pulled_image}`)
      }
    }
    
    return result
  }

  /**
   * 执行容器重建步骤
   */
  async _executeContainerRebuildStep(stepData) {
    const context = this.store.getStepContext()
    const actionType = stepData.actionType || context.actionType
    const containerName = stepData.containerName || context.containerName
    const fullImageUrl = stepData.fullImageUrl || context.fullImageUrl
    const schoolName = stepData.schoolName || context.schoolName
    
    if (!actionType || !containerName || !fullImageUrl || !schoolName) {
      throw new Error('缺少必要参数，请先执行前置步骤')
    }
    
    this.store.addLog('info', `开始智能容器重建 (操作类型: ${actionType})...`)
    
    const response = await apiClient.post('/api/intelligent-updates/v2/container-rebuild', {
      action_type: actionType,
      container_name: containerName,
      image_url: fullImageUrl,
      school_name: schoolName
    })
    const result = response.data
    
    if (result.success) {
      this.store.addLog('success', `容器操作完成: ${result.message}`)
    }
    
    return result
  }

  /**
   * 开始进度监听
   */
  _startProgressMonitoring() {
    if (this.progressInterval) {
      clearInterval(this.progressInterval)
    }
    
    this.progressInterval = setInterval(async () => {
      try {
        const response = await apiClient.get('/api/v2/status/update-progress')
        const progressResult = response.data
        if (progressResult.success) {
          this._updateProgressFromStatus(progressResult.data)
        }
      } catch (error) {
        console.warn('获取进度更新失败:', error)
      }
    }, 2000) // 每2秒检查一次进度
    
    // 10分钟后停止监听
    setTimeout(() => {
      if (this.progressInterval) {
        clearInterval(this.progressInterval)
        this.progressInterval = null
      }
    }, 600000)
  }

  /**
   * 根据状态更新进度
   */
  _updateProgressFromStatus(statusData) {
    if (!this.store) return
    
    // 根据状态数据更新前端状态
    // 这里需要根据实际的状态数据结构来实现
    const progress = statusData.progress || 0
    const message = statusData.message || ''
    
    this.store.setProgress(progress)
    this.store.setCurrentMessage(message)
    
    // 如果有日志更新，添加到日志中
    if (statusData.logs && Array.isArray(statusData.logs)) {
      statusData.logs.forEach(log => {
        this.store.addLog(log.level || 'info', log.message)
      })
    }
  }

  /**
   * 停止进度监听
   */
  stopProgressMonitoring() {
    if (this.progressInterval) {
      clearInterval(this.progressInterval)
      this.progressInterval = null
    }
  }

  /**
   * 获取步骤显示名称
   */
  getStepDisplayName(stepType) {
    const stepNames = {
      [STEP_TYPES.LWX_PARSE]: 'LWX平台数据解析',
      [STEP_TYPES.IMAGE_VERIFY]: '智能镜像版本校验',
      [STEP_TYPES.CONDITIONAL_PULL]: '条件性镜像拉取',
      [STEP_TYPES.CONTAINER_REBUILD]: '智能容器重建'
    }
    
    return stepNames[stepType] || stepType
  }

  /**
   * 获取操作类型显示名称
   */
  getActionTypeDisplayName(actionType) {
    const actionNames = {
      [ACTION_TYPES.NONE]: '无需操作',
      [ACTION_TYPES.RESTART]: '重启容器',
      [ACTION_TYPES.UPDATE]: '更新镜像',
      [ACTION_TYPES.REBUILD]: '重建容器',
      [ACTION_TYPES.CREATE]: '创建容器'
    }
    
    return actionNames[actionType] || actionType
  }
}

// 创建单例实例
export const imageUpdateService = new ImageUpdateService()

export default imageUpdateService